#!/bin/bash

# 安全Token功能测试构建脚本
# 用于编译和测试新的Token安全存储功能

echo "=== 安全Token功能测试构建脚本 ==="
echo "构建时间: $(date)"
echo "操作系统: $(uname -s)"
echo "架构: $(uname -m)"
echo ""

# 设置项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$PROJECT_ROOT/build_test_securetoken"

echo "项目根目录: $PROJECT_ROOT"
echo "构建目录: $BUILD_DIR"
echo ""

# 清理旧的构建目录
if [ -d "$BUILD_DIR" ]; then
    echo "清理旧构建目录..."
    rm -rf "$BUILD_DIR"
fi

# 创建新的构建目录
echo "创建构建目录..."
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

echo "当前工作目录: $(pwd)"
echo ""

# 检查Qt6安装
echo "检查Qt6安装..."
if command -v qmake6 &> /dev/null; then
    QMAKE_CMD="qmake6"
    echo "找到qmake6: $(which qmake6)"
elif command -v qmake &> /dev/null; then
    QMAKE_CMD="qmake"
    echo "找到qmake: $(which qmake)"
    # 检查Qt版本
    QT_VERSION=$(qmake -v | grep -oP 'Qt version \K[0-9]+\.[0-9]+')
    echo "Qt版本: $QT_VERSION"
else
    echo "错误: 未找到Qt安装，请确保Qt6已正确安装"
    exit 1
fi

echo ""

# 检查CMake
echo "检查CMake..."
if command -v cmake &> /dev/null; then
    echo "找到CMake: $(which cmake)"
    CMAKE_VERSION=$(cmake --version | head -n1)
    echo "CMake版本: $CMAKE_VERSION"
else
    echo "警告: 未找到CMake，将使用qmake构建"
fi

echo ""

# 方法1: 使用CMake构建（推荐）
echo "=== 方法1: 使用CMake构建 ==="
if command -v cmake &> /dev/null; then
    echo "配置CMake项目..."
    cmake "$PROJECT_ROOT" \
        -DCMAKE_BUILD_TYPE=Debug \
        -DCMAKE_PREFIX_PATH="/usr/local/qt6" \
        -DQT6_DIR="/usr/local/qt6/lib/cmake/Qt6" \
        -DCMAKE_INSTALL_PREFIX="$BUILD_DIR/install"

    if [ $? -eq 0 ]; then
        echo "CMake配置成功，开始编译..."
        make -j$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)

        if [ $? -eq 0 ]; then
            echo "✓ CMake构建成功"

            # 检查主程序
            if [ -f "bin/LongImageReader" ]; then
                echo "✓ 主程序编译成功: bin/LongImageReader"
            else
                echo "✗ 主程序编译失败"
            fi

        else
            echo "✗ CMake编译失败"
        fi
    else
        echo "✗ CMake配置失败"
    fi
else
    echo "跳过CMake构建（未安装CMake）"
fi

echo ""

# 方法2: 创建独立的Token测试程序
echo "=== 方法2: 构建独立Token测试程序 ==="

# 创建简化的CMakeLists.txt用于测试
cat > CMakeLists_token_test.txt << 'EOF'
cmake_minimum_required(VERSION 3.16)
project(SecureTokenTest)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt6 COMPONENTS Core Network REQUIRED)

set(SOURCES
    ../securetokenmanager.cpp
    ../configmanager.cpp
    ../app_version.cpp
    ../protection.cpp
    test_securetoken.cpp
)

set(HEADERS
    ../securetokenmanager.h
    ../configmanager.h
    ../app_version.h
    ../protection.h
)

add_executable(test_securetoken ${SOURCES} ${HEADERS})

target_link_libraries(test_securetoken Qt6::Core Qt6::Network)

# 添加编译定义
target_compile_definitions(test_securetoken PRIVATE
    QT_DEPRECATED_WARNINGS
    QT_DISABLE_DEPRECATED_BEFORE=0x060000
)
EOF

echo "创建Token测试程序的CMake配置..."

# 添加必要的源文件创建
echo "创建缺失的源文件..."

# 创建app_version.cpp（如果不存在）
if [ ! -f "$PROJECT_ROOT/app_version.cpp" ]; then
    cat > "$PROJECT_ROOT/app_version.cpp" << 'EOF'
#include "app_version.h"

namespace LimeReader {
namespace AppVersion {
    QString getAppVersion() {
        return "2.7.2-test";
    }

    QString getUserAgent() {
        return QString("LimeReader/%1 (SecureToken Test)").arg(getAppVersion());
    }
}
}
EOF
fi

# 创建app_version.h（如果不存在）
if [ ! -f "$PROJECT_ROOT/app_version.h" ]; then
    cat > "$PROJECT_ROOT/app_version.h" << 'EOF'
#ifndef APP_VERSION_H
#define APP_VERSION_H

#include <QString>

namespace LimeReader {
namespace AppVersion {
    QString getAppVersion();
    QString getUserAgent();
}
}

#endif // APP_VERSION_H
EOF
fi

echo "配置Token测试程序..."
cmake -f CMakeLists_token_test.txt "$PROJECT_ROOT" \
    -DCMAKE_BUILD_TYPE=Debug

if [ $? -eq 0 ]; then
    echo "编译Token测试程序..."
    make test_securetoken

    if [ $? -eq 0 ] && [ -f "test_securetoken" ]; then
        echo "✓ Token测试程序编译成功"
        echo ""
        echo "=== 运行Token安全存储测试 ==="
        echo "测试程序路径: $(pwd)/test_securetoken"
        echo ""

        # 运行测试
        ./test_securetoken
        TEST_RESULT=$?

        echo ""
        if [ $TEST_RESULT -eq 0 ]; then
            echo "✓ Token安全存储测试通过"
        else
            echo "✗ Token安全存储测试失败 (退出码: $TEST_RESULT)"
        fi
    else
        echo "✗ Token测试程序编译失败"
    fi
else
    echo "✗ Token测试程序配置失败"
fi

echo ""

# 方法3: 手动编译（备用方案）
echo "=== 方法3: 手动编译测试 ==="

if command -v g++ &> /dev/null; then
    echo "找到g++编译器: $(which g++)"
    echo "尝试手动编译..."

    # 查找Qt6头文件和库
    QT6_PATHS=(
        "/usr/local/qt6"
        "/usr/include/qt6"
        "/opt/qt6"
        "$HOME/Qt6"
    )

    QT6_FOUND=""
    for path in "${QT6_PATHS[@]}"; do
        if [ -d "$path" ]; then
            QT6_FOUND="$path"
            break
        fi
    done

    if [ -n "$QT6_FOUND" ]; then
        echo "找到Qt6路径: $QT6_FOUND"

        # 手动编译命令
        g++ -std=c++17 \
            -I"$PROJECT_ROOT" \
            -I"$QT6_FOUND/include" \
            -I"$QT6_FOUND/include/QtCore" \
            -I"$QT6_FOUND/include/QtNetwork" \
            -L"$QT6_FOUND/lib" \
            ../securetokenmanager.cpp \
            ../configmanager.cpp \
            test_securetoken.cpp \
            -lQt6Core -lQt6Network \
            -o test_securetoken_manual

        if [ $? -eq 0 ]; then
            echo "✓ 手动编译成功"

            if [ -f "test_securetoken_manual" ]; then
                echo "运行手动编译的测试程序..."
                ./test_securetoken_manual
            fi
        else
            echo "✗ 手动编译失败"
        fi
    else
        echo "未找到Qt6安装路径"
    fi
else
    echo "未找到g++编译器"
fi

echo ""

# 清理临时文件
echo "清理临时文件..."
rm -f CMakeLists_token_test.txt

echo ""
echo "=== 构建测试总结 ==="
echo "构建目录: $BUILD_DIR"
echo "项目根目录: $PROJECT_ROOT"
echo ""

# 检查生成的文件
echo "生成的文件:"
find "$BUILD_DIR" -name "*test*" -type f -executable 2>/dev/null | while read file; do
    echo "  ✓ $file"
done

echo ""
echo "配置文件检查:"
if [ -f "$PROJECT_ROOT/config.json" ]; then
    echo "  ✓ 找到配置文件: config.json"
    echo "  文件大小: $(du -h "$PROJECT_ROOT/config.json" | cut -f1)"
else
    echo "  - 未找到配置文件"
fi

echo ""
echo "=== 下一步操作建议 ==="
echo "1. 检查测试结果，确保所有功能正常"
echo "2. 查看生成的配置文件格式"
echo "3. 在主程序中集成安全Token功能"
echo "4. 部署到生产环境前进行充分测试"
echo ""

echo "构建脚本执行完成！"